package system.elements;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JTextField;

public class ControlTextField extends JTextField {

	private final Pattern finalPattern = Pattern.compile("(-)?[0-9]+((\\.)[0-9]+)?");
	private Color oldColor = null;
	public ControlTextField() {
		super();
		
		this.addFocusListener(new FocusListener() {
			
			@Override
			public void focusLost(FocusEvent arg0) {
				checkContent();
			}
			
			@Override
			public void focusGained(FocusEvent arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void checkContent()
	{
		String content = getText();
		setText(content.replaceAll(",", "."));
		Matcher m = finalPattern.matcher(getText());
		if (!m.matches()) {
			oldColor = getBackground() == Color.RED? oldColor : getBackground();
			setBackground(Color.RED);
		}
		else
		{
			setBackground(oldColor);
		}
	}

}
